package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.TemplateReview;
import com.micro.ai.template.service.TemplateReviewService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 模板审核Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/template/reviews")
@RequiredArgsConstructor
@Tag(name = "模板审核管理", description = "模板审核相关接口")
public class TemplateReviewController {

    private final TemplateReviewService templateReviewService;

    @PostMapping("/template/{templateId}")
    @PreAuthorize("hasAuthority('template:review:submit')")
    @Operation(summary = "提交审核", description = "提交模板审核申请")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "提交成功",
            content = @Content(schema = @Schema(implementation = TemplateReview.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "模板已在审核中"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<TemplateReview> submitReview(
            @Parameter(description = "模板ID") @PathVariable String templateId,
            Authentication authentication) {
        String userId = authentication.getName();
        log.info("提交审核请求, templateId: {}, userId: {}", templateId, userId);
        return ApiResponse.success(templateReviewService.submitReview(templateId, userId));
    }

    @PostMapping("/{reviewId}/approve")
    @PreAuthorize("hasAuthority('template:review:approve')")
    @Operation(summary = "审核通过", description = "审核通过模板")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "审核成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "审核状态不允许操作"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "审核记录不存在")
    })
    public ApiResponse<Void> approveReview(
            @Parameter(description = "审核ID") @PathVariable String reviewId,
            @RequestBody Map<String, String> params,
            Authentication authentication) {
        String reviewerId = authentication.getName();
        String comment = params.get("comment");
        
        log.info("审核通过请求, reviewId: {}, reviewerId: {}", reviewId, reviewerId);
        templateReviewService.approveReview(reviewId, reviewerId, comment);
        return ApiResponse.<Void>success(null);
    }

    @PostMapping("/{reviewId}/reject")
    @PreAuthorize("hasAuthority('template:review:approve')")
    @Operation(summary = "审核拒绝", description = "拒绝模板审核")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "拒绝成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "审核状态不允许操作"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "审核记录不存在")
    })
    public ApiResponse<Void> rejectReview(
            @Parameter(description = "审核ID") @PathVariable String reviewId,
            @RequestBody Map<String, String> params,
            Authentication authentication) {
        String reviewerId = authentication.getName();
        String comment = params.get("comment");
        
        log.info("审核拒绝请求, reviewId: {}, reviewerId: {}", reviewId, reviewerId);
        templateReviewService.rejectReview(reviewId, reviewerId, comment);
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/pending")
    @PreAuthorize("hasAuthority('template:review:query')")
    @Operation(summary = "查询待审核列表", description = "分页查询待审核的模板列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<IPage<TemplateReview>> getPendingReviews(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
        Page<TemplateReview> page = new Page<>(current, size);
        return ApiResponse.success(templateReviewService.getPendingReviews(page));
    }

    @GetMapping("/template/{templateId}/history")
    @PreAuthorize("hasAuthority('template:review:query')")
    @Operation(summary = "查询审核历史", description = "查询模板的审核历史记录")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<List<TemplateReview>> getTemplateReviewHistory(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        return ApiResponse.success(templateReviewService.getTemplateReviewHistory(templateId));
    }

    @GetMapping("/template/{templateId}/current")
    @PreAuthorize("hasAuthority('template:review:query')")
    @Operation(summary = "查询当前审核状态", description = "查询模板的当前审核状态")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = TemplateReview.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在或无审核记录")
    })
    public ApiResponse<TemplateReview> getCurrentReview(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        return ApiResponse.success(templateReviewService.getCurrentReview(templateId));
    }
}

